<template>
  <div class="category-list-container">
    <el-card>
      <!-- 操作按钮 -->
      <div class="table-top">
        <el-button type="primary" @click="handleAdd">新增管理员</el-button>
        <el-button
          type="danger"
          :disabled="selectedRows.length === 0"
          @click="handleDeleteSelected"
        >
          批量删除({{ selectedRows.length }})
        </el-button>
      </div>

      <!-- 用户表格 -->
      <el-table
        :data="categoryList"
        stripe
        style="width: 100%"
        @selection-change="handleSelectionChange"
      >
        <!-- 复选框列 -->
        <el-table-column type="selection" width="55" align="center"></el-table-column>

        <el-table-column prop="uId" label="ID" width="60" align="center" />
        <el-table-column prop="uName" label="真实姓名" min-width="200" />
        <el-table-column prop="uUsername" label="用户名" min-width="150" />
        <el-table-column prop="createTime" label="创建时间" width="170" align="center" />
        <el-table-column prop="updateTime" label="更新时间" width="170" align="center" />

        <el-table-column label="操作" width="150" align="center">
          <template #default="{ row }">
            <el-button size="small" type="primary" link @click="handleEdit(row)">编辑</el-button>
            <el-button size="small" type="danger" link @click="handleDelete(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 分页 -->
    <div class="pagination-container">
      <el-pagination
        layout="prev, pager, next"
        :total="total"
        :current-page="currentPage"
        :page-size="pageSize"
        @current-change="handlePageChange"
      />
    </div>

    <!-- 弹窗：新增/编辑用户 -->
    <el-dialog v-model="dialogVisible" :title="dialogTitle" width="40%">
      <el-form ref="form" :model="formData" label-width="100px">
        <el-form-item label="用户名">
          <el-input v-model="formData.name" placeholder="请输入用户名" />
        </el-form-item>
        <el-form-item label="账号">
          <el-input v-model="formData.username" placeholder="请输入账号" />
        </el-form-item>
        <el-form-item label="密码" v-if="!isEdit">
          <el-input v-model="formData.password" type="password" placeholder="请输入密码" />
        </el-form-item>
        <!-- 职位下拉框 -->
        <el-form-item label="职位">
          <el-select v-model="formData.positionId" placeholder="请选择职位" style="width: 100%" @change="handlePositionChange">
            <el-option
              v-for="item in positionOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit">确认</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import controller from '@/api/controller'

export default {
  name: 'UserListView',
  data() {
    return {
      categoryList: [],
      total: 0,
      currentPage: 1,
      pageSize: 10,
      dialogVisible: false,
      dialogTitle: '',
      isEdit: false,
      selectedRows: [],

      formData: {
        id: null,
        name: '',
        username: '',
        password: '',
        positionId: null,
        positionIdLabel: '' // 存储职位名用于提交
      },

      positionOptions: []
    }
  },
  mounted() {
    this.getCategoryListPage()
    this.fetchPositions()
  },
  methods: {
    async fetchPositions() {
      try {
        const res = await controller.getAllPosition()
        if (res && res.code === 200) {
          this.positionOptions = res.data.map((name, index) => ({
            label: name,
            value: index + 1
          }))
        } else {
          this.$message.error('获取职位失败')
        }
      } catch (error) {
        console.error('获取职位失败:', error)
        this.$message.error('网络异常，请稍后再试')
      }
    },

    handlePositionChange(value) {
      const selected = this.positionOptions.find(p => p.value === value)
      if (selected) {
        this.formData.positionIdLabel = selected.label
      }
    },

    async getCategoryListPage(page = 1) {
      try {
        const res = await controller.getCustomer(page, this.pageSize)
        if (res && res.records) {
          this.categoryList = res.records.map(item => ({
            uId: item.uId,
            uName: item.uName,
            uUsername: item.uUsername,
            positionName: item.positionName
          }))
          this.total = res.total
          this.currentPage = page
        } else {
          this.$message.error('获取用户列表失败')
        }
      } catch (error) {
        console.error(error)
        this.$message.error('请求失败，请检查网络')
      }
    },

    handleAdd() {
      this.formData = {
        id: null,
        name: '',
        username: '',
        password: '',
        positionId: null,
        positionIdLabel: ''
      }
      this.dialogTitle = '新增管理员'
      this.isEdit = false
      this.dialogVisible = true
    },

    handleEdit(row) {
      const matched = this.positionOptions.find(p => p.label === row.positionName)

      this.formData = {
        id: row.uId,
        name: row.uName,
        username: row.uUsername,
        positionId: matched ? matched.value : null,
        positionIdLabel: matched ? matched.label : ''
      }

      this.dialogTitle = '编辑管理员'
      this.isEdit = true
      this.dialogVisible = true
    },

    async handleSubmit() {
  this.$refs.form.validate(async valid => {
    if (valid) {
      try {
        const staffEntity = {
          uId: this.formData.id,
          uName: this.formData.name,
          uUsername: this.formData.username,
          uPassword: this.formData.password,
          positionName: this.formData.positionIdLabel,
          uStatus: true,
          uDelflag: false,
          uCreateTime: new Date().toISOString(),
          uUpdateTime: new Date().toISOString()
        }

        // 自动填充创建人和更新人
        const currentUser = this.$store.getters.getUserInfo?.username || '未知用户'
        if (!this.isEdit) {
          staffEntity.uCreateUser = currentUser
        }
        staffEntity.uUpdateUser = currentUser

        let res
        if (this.isEdit) {
          res = await controller.updateUser(staffEntity)
        } else {
          res = await controller.addAdmin(staffEntity)
        }

        if (res && res.code === 200) {
          this.$message.success(this.isEdit ? '更新成功' : '新增成功')
          this.dialogVisible = false
          this.getCategoryListPage(this.currentPage)
        } else {
          this.$message.error(this.isEdit ? '更新失败' : '新增失败')
        }
      } catch (error) {
        console.error('提交失败:', error)
        this.$message.error('请求失败，请检查网络')
      }
    } else {
      return false
    }
  })
},

    async handleDelete(row) {
      this.$confirm(`确定要删除管理员 "${row.uName}" 吗？`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        const res = await controller.deleteAdmins([row.uId])
        if (res && res.code === 200) {
          this.$message.success('删除成功')
          this.getCategoryListPage(this.currentPage)
        } else {
          this.$message.error('删除失败')
        }
      }).catch(() => {
        this.$message.info('已取消删除')
      })
    },

    async handleDeleteSelected() {
      if (this.selectedRows.length === 0) {
        this.$message.warning('请至少选择一行')
        return
      }

      const ids = this.selectedRows.map(row => row.uId)

      try {
        const confirmResult = await this.$confirm(
          `确定要删除选中的 ${ids.length} 位管理员吗？`,
          '提示',
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }
        )

        if (confirmResult === 'confirm') {
          const res = await controller.deleteAdmins(ids)
          if (res && res.code === 200) {
            this.$message.success('删除成功')
            this.getCategoryListPage(this.currentPage)
            this.selectedRows = []
          } else {
            this.$message.error('删除失败')
          }
        }
      } catch (error) {
        this.$message.error('操作失败，请稍后再试'+error)
      }
    },

    handlePageChange(page) {
      this.currentPage = page
      this.getCategoryListPage(page)
    },

    handleSelectionChange(rows) {
      this.selectedRows = rows
    }
  }
}
</script>

<style scoped>
.category-list-container {
  padding: 20px;
}

.table-top {
  margin-bottom: 15px;
}

.pagination-container {
  margin-top: 20px;
  text-align: right;
}
</style>